﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using Com.DAO;
using Com.Data;
using Centaline.WebControl;
using System.Text;

using WF.BusinessObject;
using System.DirectoryServices;
using System.Net.Mail;
using System.Web.UI;

namespace WF.Common
{
    /// <summary>
    /// 用于编写工具方法、静态方法

    /// </summary>
    public class CentaUtil
    {
        static CentaUtil()
        {
        }

        #region 控件绑定
        /// <summary>
        /// 根据sql语句绑定DropDownList控件
        /// </summary>
        /// <param name="list"></param>
        /// <param name="displayColumn"></param>
        /// <param name="valueColumn"></param>
        /// <param name="sql"></param>
        /// <param name="dataManager"></param>
        public static void BindDropDownList(DropDownList list, string textField, string valueField, string sql, DataManager dataManager)
        {
            try
            {
                DataSet ds = SelectDataSet(dataManager, sql);
                list.DataSource = ds.Tables[0].DefaultView;
                list.DataTextField = textField;
                list.DataValueField = valueField;
                list.DataBind();
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 根据sql语句绑定DropDownList控件
        /// </summary>
        /// <param name="list"></param>
        /// <param name="displayColumn"></param>
        /// <param name="valueColumn"></param>
        /// <param name="sql"></param>
        /// <param name="dataManager"></param>
        public static void BindDropDownList(DropDownList list, string textField, string valueField, DataSet ds)
        {
            try
            {
                list.DataSource = ds.Tables[0].DefaultView;
                list.DataTextField = textField;
                list.DataValueField = valueField;
                list.DataBind();
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 根据sql语句绑定DropDownList控件
        /// </summary>
        /// <param name="list"></param>
        /// <param name="textField"></param>
        /// <param name="valueField"></param>
        /// <param name="sql"></param>
        /// <param name="dataManager"></param>
        /// <param name="isBlankItem">是否插入空行</param>
        public static void BindDropDownList(DropDownList list, string textField, string valueField, string sql, DataManager dataManager, bool isBlankItem)
        {
            try
            {
                BindDropDownList(list, textField, valueField, sql, dataManager);
                if (isBlankItem)
                {
                    ListItem item = new ListItem("--请选择--", "");
                    list.Items.Insert(0, item);
                }
            }
            catch
            {
                throw;
            }
        }

        public static void BindDropDownList(DropDownList list, string textField, string valueField, DataSet ds, bool isBlankItem)
        {
            try
            {
                BindDropDownList(list, textField, valueField, ds);
                if (isBlankItem)
                {
                    ListItem item = new ListItem("--请选择--", "");
                    list.Items.Insert(0, item);
                }
            }
            catch
            {
                throw;
            }
        }
        /// <summary>
        /// 执行sql语句，绑定DataGrid
        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="dataGrid"></param>
        /// <param name="sql"></param>
        public static void BindDataGrid(DataManager dataManager, CentaDataGrid dataGrid, string sql)
        {
            try
            {
                DataSet ds = SelectDataSet(dataManager, sql);
                dataGrid.DataSource = ds.Tables[0].DefaultView;
                dataGrid.DataBind();
            }
            catch
            {
                throw;
            }
        }

        public static void BindDataGridByDataAccess(DataAccess dataAccess, CentaDataGrid dataGrid)
        {
            DataSet ds = dataAccess.GetDataSet();
            dataGrid.DataSource = ds.Tables[0].DefaultView;
            dataGrid.DataBind();
        }

        /// <summary>
        /// 执行sql语句，绑定ListControl
        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="list"></param>
        /// <param name="sql"></param>
        /// <param name="valueField"></param>
        /// <param name="textField"></param>
        public static void BindListControl(DataManager dataManager, ListControl list, string sql, string valueField, string textField, string blankItem)
        {
            DataSet ds = SelectDataSet(dataManager, sql);
            list.DataSource = ds.Tables[0].DefaultView;
            list.DataTextField = textField;
            list.DataValueField = valueField;
            list.DataBind();
            if (blankItem != "")
            {
                ListItem item = new ListItem(blankItem, "");
                list.Items.Insert(0, item);
            }
        }
        #endregion 控件绑定

        #region DataBase
        /// <summary>
        /// 执行sql语句，返回DataReader
        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static SqlDataReader SelectDataReader(DataManager dataManager, string sql)
        {
            try
            {
                SqlCommand com = null;
                if (dataManager.IsBeginTrasaction)
                {
                    com = new SqlCommand(sql, dataManager.Connection(), dataManager.GetTransaction());
                }
                else
                {
                    com = new SqlCommand(sql, dataManager.Connection());
                }
                SqlDataReader rs = com.ExecuteReader();
                return rs;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 执行sql语句，返回DataSet
        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataSet SelectDataSet(DataManager dataManager, string sql)
        {
            try
            {
                SqlCommand cmd = null;
                if (dataManager.IsBeginTrasaction)
                {
                    cmd = new SqlCommand(sql, dataManager.Connection(), dataManager.GetTransaction());
                }
                else
                {
                    cmd = new SqlCommand(sql, dataManager.Connection());
                }
                //SqlDataAdapter com = new SqlDataAdapter(sql ,dataManager.Connection());
                cmd.CommandTimeout = 90;
                SqlDataAdapter com = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                com.Fill(ds);
                return ds;
            }
            catch
            {
                throw;
            }
        }

        public static string SelectScale(DataManager dataManager, string sql)
        {
            SqlCommand cmd = null;
            if (dataManager.IsBeginTrasaction)
            {
                cmd = new SqlCommand(sql, dataManager.Connection(), dataManager.GetTransaction());
            }
            else
            {
                cmd = new SqlCommand(sql, dataManager.Connection());
            }

            object rtn = cmd.ExecuteScalar();
            if (rtn != null)
            {
                return cmd.ExecuteScalar().ToString();
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 执行sql语句，检查结果集是否为空
        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static bool IsHaveResult(DataManager dataManager, string sql)
        {
            bool rtn = false;
            SqlDataReader rs = dataManager.selectReader(sql);
            if (rs.Read())
            {
                rtn = true;
            }
            rs.Close();
            return rtn;
        }

        /// <summary>
        /// 根据主键获取指定表指定字段的值

        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="tableName"></param>
        /// <param name="propertyName"></param>
        /// <param name="keyName"></param>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public static string GetPropertyValueByKeyValue(DataManager dataManager, string tableName, string propertyName, string keyName, string keyValue)
        {
            string rtn;
            string sql = "select " + propertyName + " from " + tableName + " where " + keyName + " ='" + keyValue + "'";
            SqlDataReader rs = dataManager.selectReader(sql);
            if (rs.Read())
            {
                rtn = rs[propertyName].ToString();
            }
            else
            {
                rtn = null;
            }
            rs.Close();
            return rtn;
        }

        /// <summary>
        ///  设置某个表的某列值

        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="tableName"></param>
        /// <param name="propertyName"></param>
        /// <param name="keyName"></param>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public static bool SetPropertyValueByKeyValue(DataManager dataManager, string tableName, string propertyName, string setValue, string keyName, string keyValue)
        {
            string sql = " Update " + tableName + " Set " + propertyName + "='" + setValue + "' Where " + keyName + " ='" + keyValue + "'";
            try
            {
                dataManager.Execute(sql);
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 形成本实体的SQL语句
        /// </summary>
        /// <returns></returns>
        public static string ToSQL(BusinessEntiry businessEntiry)
        {
            string rtn = "";
            string fieldsString = "";
            string valuesString = "";
            string setString = "";
            Column p_Columns = null;
            try
            {
                p_Columns = businessEntiry.Columns;
                if (p_Columns == null)
                    return rtn;

                if (businessEntiry.EntityStatus == EntityStatus.Delete)
                {
                    rtn = "delete from [" + businessEntiry.TableName + "]";
                    rtn += " where " + GetKeyWhere(businessEntiry);
                }
                else
                {
                    rtn += " if EXISTS (select * from [" + businessEntiry.TableName + "]";
                    rtn += " where " + GetKeyWhere(businessEntiry) + ")";
                    //存在该条记录，Update相应的记录

                    rtn += " begin ";
                    for (int i = 0; i < p_Columns.Count; i++)
                    {
                        if (p_Columns[i].Value != "")
                        {
                            switch (p_Columns[i].Type)
                            {
                                case Com.Data.DataType.Money:
                                    setString += "," + p_Columns[i].ColumnName + "=" + "convert(money,'" + p_Columns[i].Value + "')";
                                    break;

                                default:
                                    setString += "," + p_Columns[i].ColumnName + "=" + "'" + p_Columns[i].Value.Replace("'", "''") + "'";
                                    break;
                            }
                        }
                    }

                    if (setString.Length != 0)
                    {
                        setString = setString.Substring(1);
                        rtn += "update [" + businessEntiry.TableName + "]";
                        rtn += " set " + setString + " where " + GetKeyWhere(businessEntiry);
                    }
                    rtn += " end ";
                    //不存在该条记录，新增一条记录

                    rtn += " else ";
                    rtn += " begin ";
                    for (int i = 0; i < p_Columns.Count; i++)
                    {
                        if (p_Columns[i].Value != "")
                        {
                            fieldsString += "," + p_Columns[i].ColumnName;
                            switch (p_Columns[i].Type)
                            {
                                case Com.Data.DataType.Money:
                                    valuesString += "," + "convert(money,'" + p_Columns[i].Value + "')";
                                    break;

                                default:
                                    valuesString += "," + "'" + p_Columns[i].Value.Replace("'", "''") + "'";
                                    break;
                            }
                        }
                    }

                    if (fieldsString.Length != 0)
                    {
                        fieldsString = fieldsString.Substring(1);
                        valuesString = valuesString.Substring(1);
                        rtn += "insert into [" + businessEntiry.TableName + "] (" + fieldsString + ")";
                        rtn += " values(" + valuesString + ") ";
                    }
                    rtn += " end ";
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

            return rtn;
        }

        public static string GetKeyWhere(Com.DAO.BusinessEntiry businessEntiry)
        {
            string rtn = "";
            try
            {
                Com.DAO.Column p_Columns = businessEntiry.Columns;
                if (p_Columns != null)
                {
                    for (int i = 0; i < p_Columns.Count; i++)
                    {
                        if (p_Columns[i].IsKey)
                        {
                            if (p_Columns[i].Value == "")
                                throw new Exception(businessEntiry.TableName + "：缺少“" + p_Columns[i].ColumnName + "”字段");
                            else
                            {
                                if (rtn.Length == 0)
                                {
                                    rtn = p_Columns[i].ColumnName + "='" + p_Columns[i].Value + "'";
                                }
                                else
                                {
                                    rtn = rtn + " and " + p_Columns[i].ColumnName + "='" + p_Columns[i].Value + "'";
                                }
                            }
                        }
                    }
                }

                if (rtn.Length == 0)
                {
                    throw new Exception(businessEntiry.TableName + "：没有设置主关键字");
                }

                return rtn;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion DataBase

        #region 参数及控件输入值检查

        /// <summary>
        /// 检查参数

        /// </summary>
        /// <param name="param"></param>
        public static void CheckParam(object param, string paramName)
        {
            if (param == null)
            {
                throw new BusinessException("参数[" + paramName + "]不能为空");
            }
        }

        public static bool IsParamNull(string param)
        {
            return param == null || param == "";
        }

        /// <summary>
        /// 检查控件值

        /// </summary>
        /// <param name="controlValue"></param>
        /// <returns></returns>
        public static string CheckControlValue(string controlValue)
        {
            //			if(controlValue != null)
            //			{
            //				return controlValue.Replace("<" ,"&lt;").Replace(">" ,"&gt;").Replace("'" ,"''");
            //			}
            //			else
            //			{
            //				return null;
            //			}
            return controlValue.Trim().Replace("'", "''");
        }

        /// <summary>
        /// 检查日期范围是否输入正确

        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public static bool CheckDateBound(TextBox start, TextBox end)
        {
            bool rtn = false;
            if (start.Text.Trim() != "")
            {
                try
                {
                    DateTime.Parse(CentaUtil.Date8To10(start.Text.Trim()));
                }
                catch
                {
                    throw new Exception("日期值[" + start.Text.Trim() + "]无效");
                }
            }
            if (end.Text.Trim() != "")
            {
                try
                {
                    DateTime.Parse(CentaUtil.Date8To10(end.Text.Trim()));
                }
                catch
                {
                    throw new Exception("日期值[" + end.Text.Trim() + "]无效");
                }
            }
            if (start.Text.Trim() == "" && end.Text.Trim() == "")
                rtn = true;
            else if (start.Text.Trim() == "" && end.Text.Trim() != "")
            {
                string to = CentaUtil.Date8To10(end.Text.Trim());
                DateTime date = DateTime.Parse(to);
                start.Text = date.AddMonths(-1).ToString("yyyyMMdd");
                rtn = true;
            }
            else if (start.Text.Trim() != "" && end.Text.Trim() == "")
            {
                end.Text = start.Text.Trim();
                rtn = true;
            }
            else if (start.Text.Trim() != "" && end.Text.Trim() != "")
            {
                if (int.Parse(start.Text.Trim()) > int.Parse(end.Text.Trim()))
                {
                    string temp = start.Text.Trim();
                    start.Text = end.Text.Trim();
                    end.Text = temp;
                }
                rtn = true;
            }
            return rtn;
        }

        /// <summary>
        /// 检查数字范围是否输入正确

        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        public static bool CheckNumberBound(TextBox start, TextBox end, string description)
        {
            bool rtn = false;
            if (start.Text.Trim() == "" && end.Text.Trim() == "")
                rtn = true;
            else if (start.Text.Trim() == "" && end.Text.Trim() != "")
            {
                if (decimal.Parse(end.Text.Trim()) < 0)
                {
                    throw new Exception(description + "不能小于0！");
                }
                else
                {
                    start.Text = "0";
                    rtn = true;
                }
            }
            else if (start.Text.Trim() != "" && end.Text.Trim() == "")
            {
                if (decimal.Parse(start.Text.Trim()) < 0)
                {
                    throw new Exception(description + "不能小于0！");
                }
                else
                {
                    end.Text = start.Text.Trim();
                    rtn = true;
                }
            }
            else if (start.Text.Trim() != "" && end.Text.Trim() != "")
            {
                if (decimal.Parse(start.Text.Trim()) < 0 || decimal.Parse(end.Text.Trim()) < 0)
                {
                    throw new Exception(description + "不能小于0！");
                }
                if (decimal.Parse(start.Text.Trim()) > decimal.Parse(end.Text.Trim()))
                {
                    string temp = start.Text.Trim();
                    start.Text = end.Text.Trim();
                    end.Text = temp;
                    rtn = true;
                }
                else
                    rtn = true;
            }
            return rtn;
        }
        #endregion

        #region 生成GUID
        /// <summary>
        /// 生成GUID
        /// </summary>
        /// <returns></returns>
        public static string GetNewGUID()
        {
            return System.Guid.NewGuid().ToString().ToUpper();
        }

        /// <summary>
        /// 生成32位字符串类型的ID，根据三级市场系统算法

        /// </summary>
        /// <returns></returns>
        public static string GenVarcharGUID()
        {
            return GetNewGUID().Replace("-", "");
        }
        #endregion

        #region 身份证号码相关函数

        /// <summary>
        /// 通过身份证获得年
        /// </summary>
        /// <param name="IDCard"></param>
        /// <returns></returns>
        public static int GetYear(string IDCard)
        {
            string rtn = "0";
            if (IDCard.Length == 15)
            {
                rtn = IDCard.Substring(6, 2);
                rtn = "19" + rtn;
            }
            else if (IDCard.Length == 18)
            {
                rtn = IDCard.Substring(6, 4);
            }
            return int.Parse(rtn);
        }

        /// <summary>
        /// 通过身份证获得月
        /// </summary>
        /// <param name="IDCard"></param>
        /// <returns></returns>
        public static int GetMonth(string IDCard)
        {
            string rtn = "0";
            if (IDCard.Length == 15)
            {
                rtn = IDCard.Substring(8, 2);
            }
            else if (IDCard.Length == 18)
            {
                rtn = IDCard.Substring(10, 2);
            }
            return int.Parse(rtn);
        }

        /// <summary>
        /// 通过身份证获得日
        /// </summary>
        /// <param name="IDCard"></param>
        /// <returns></returns>
        public static int GetDay(string IDCard)
        {
            string rtn = "0";
            if (IDCard.Length == 15)
            {
                rtn = IDCard.Substring(10, 2);
            }
            else if (IDCard.Length == 18)
            {
                rtn = IDCard.Substring(12, 2);
            }
            return int.Parse(rtn);
        }

        /// <summary>
        /// 判断是否是闰年

        /// </summary>
        /// <param name="year"></param>
        /// <returns></returns>
        public static bool IsFullYear(int year)
        {
            if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获得身份证校验码
        /// </summary>
        /// <param name="IDCard"></param>
        /// <returns></returns>
        public static char GetCheckKey(string IDCard)
        {
            char[] A = new char[18];
            if (IDCard.Length == 15)
            {
                IDCard.CopyTo(0, A, 0, 6);
                A[6] = '1'; A[7] = '9';
                IDCard.CopyTo(6, A, 8, 9);
            }
            else
                IDCard.CopyTo(0, A, 0, 18);

            int[] W = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
            int sum = 0;
            for (int i = 0; i <= 16; i++)
                sum += (System.Convert.ToInt32(A[i]) - 48) * W[i];

            int z = sum % 11;

            char[] Y = new char[] { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
            return Y[z];
        }

        /// <summary>
        /// 检查香港身份证，正确返回right,错误返回错误信息
        /// </summary>
        /// <param name="IDCard"></param>
        /// <returns></returns>
        public static string CheckHKIDCard(string IDCard)
        {
            //身份证括弧中的数字或字母为校验码
            string CheckCode = IDCard.Substring(8, 1);

            string[] num = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
             "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26" };

            string[] capital = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
             "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

            //表示 身份证中的第一个字母

            string FirstLetter = IDCard.Substring(0, 1);
            //表示 身份证中的第一个字母转换成的数字

            string FirstNumber = "";
            for (int i = 0; i < capital.Length; i++)
            {
                if (FirstLetter.ToUpper() == capital[i])
                {
                    FirstNumber = num[i];
                    break;
                }
            }
            if (FirstNumber == "")
            {
                return "身份证号码格式不正确";
            }
            else
            {
                //char[] MidNumber = IDCard.Substring(1, 6).ToCharArray();
                //int sec = int.Parse(MidNumber[0].ToString());
                string MidNumber = IDCard.Substring(1, 6);
                //把身份证前七位数字分别乘以8，7，6，5，4，3，2,得到总数再除以11，得到余数

                int baseNum = 8;
                int val = int.Parse(FirstNumber) * baseNum;
                int Total = val;
                for (int i = 0; i < 6; i++)
                {
                    baseNum--;
                    val = int.Parse(MidNumber[i].ToString());
                    Total = Total + val * baseNum;
                }
                //如果整除，校验码为0，如果余数为1，则校验码为A，如果余数为2～10，则用11减去这个余数，则为校验码。

                string result = "";
                if (Total % 11 == 0)
                {
                    result = "0";
                }
                else if (Total % 11 == 1)
                {
                    result = "A";
                }
                else
                {
                    result = (11 - Total % 11).ToString();
                }
                if (result == CheckCode)
                {
                    return "right";
                }
                else
                {
                    return "身份证号码不正确";
                }
            }
        }
        /// <summary>
        /// 检查身份证是否正确，正确则返回right，错误则返回错误信息
        /// </summary>
        /// <param name="IDCard"></param>
        /// <returns></returns>
        public static string CheckIDCard(string IDCard)
        {

            IDCard = IDCard.Trim();
            if (IDCard.Length != 15 && IDCard.Length != 18)
                return "身份证位数不够！";
            for (int i = 0; (IDCard.Length == 18 ? i < IDCard.Length - 1 : i < IDCard.Length); i++)
            {
                if (IDCard.ToCharArray(i, 1)[0] < '0' || IDCard.ToCharArray(i, 1)[0] > '9')
                {
                    return "身份证中含有非法字符！";
                }
            }
            int year = GetYear(IDCard);
            if (year > DateTime.Now.Year || year < 1900)
            {
                return "身份证中出生年信息错误！";
            }
            int month = GetMonth(IDCard);
            if (month > 12 || month < 1)
            {
                return "身份证中出生月信息错误！";
            }
            int day = GetDay(IDCard);
            if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
            {
                if (day > 31 || day < 1)
                {
                    return "身份证中出生日信息错误！";
                }
            }
            else if (month != 2)
            {
                if (day > 30 || day < 1)
                {
                    return "身份证中出生日信息错误！";
                }
            }
            else
            {
                if (IsFullYear(year))
                {
                    if (day > 29 || day < 1)
                    {
                        return "身份证中出生日信息错误！";
                    }
                }
                else
                {
                    if (day > 28 || day < 1)
                    {
                        return "身份证中出生日信息错误！";
                    }
                }
            }
            if (IDCard.Length == 18 && IDCard.ToUpper().ToCharArray(17, 1)[0] != GetCheckKey(IDCard))
            {
                return "身份证中校验码出错！";
            }
            return "right";
        }

        /// <summary>
        /// 15位身份证号码转换成18位身份证号码
        /// </summary>
        /// <param name="strIDCard"></param>
        /// <returns></returns>
        public static string IDCard15To18(string strIDCard)
        {
            strIDCard = strIDCard.Trim();
            if (strIDCard.Length == 15)
            {
                char[] A = new char[18];
                strIDCard.CopyTo(0, A, 0, 6);
                A[6] = '1'; A[7] = '9';
                strIDCard.CopyTo(6, A, 8, 9);

                int[] W = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
                int sum = 0;
                for (int i = 0; i <= 16; i++)
                    sum += (System.Convert.ToInt32(A[i]) - 48) * W[i];

                int z = sum % 11;

                char[] Y = new char[] { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
                A[17] = Y[z];
                string newShenFen = new string(A);
                return newShenFen;
            }
            else
                return strIDCard;
        }

        /// <summary>
        /// 18位身份证号码转换成15位身份证号码
        /// </summary>
        /// <param name="strIDCard"></param>
        /// <returns></returns>
        public static string IDCard18To15(string strIDCard)
        {
            strIDCard = strIDCard.Trim();
            if (strIDCard.Length == 18)
            {
                strIDCard = strIDCard.Substring(0, 6) + strIDCard.Substring(8, 9);
            }
            return strIDCard;
        }

        /// <summary>
        /// 通过身份证号获得人员性别
        /// </summary>
        /// <param name="strIDCard"></param>
        /// <returns></returns>
        public static string GetSexByIDCard(string strIDCard)
        {
            string sex = "";
            if (strIDCard.Trim().Length == 15 || strIDCard.Trim().Length == 18)
            {
                strIDCard = IDCard15To18(strIDCard);
                int id = Convert.ToInt32(strIDCard.Substring(16, 1));
                int mod = id % 2;
                if (mod == 0)
                    sex = "女";
                else
                    sex = "男";
            }

            return sex;
        }

        /// <summary>
        /// 通过身份证号获得人员生日
        /// </summary>
        /// <param name="strIDCard"></param>
        /// <returns></returns>
        public static string GetBirthdayByIDCard(string strIDCard)
        {
            string birthday = "";
            if (strIDCard.Trim().Length == 15 || strIDCard.Trim().Length == 18)
            {
                strIDCard = IDCard15To18(strIDCard);
                string date = strIDCard.Substring(6, 8);
                birthday = Date8To10(date);
            }

            return birthday;
        }
        #endregion

        #region 随机数

        public static string GetRandomString()
        {
            Random random = new Random();
            return random.Next().ToString();
        }
        #endregion

        #region 去掉汉字和字母（汉字拼音的首字母）组成的混和串中的字母

        public static string CutLettersFromString(DataManager dataManager, string fixedString)
        {
            string sql = string.Format(@"Select dbo.FN_CutLettersFromString('{0}')", fixedString);
            return CentaUtil.SelectScale(dataManager, sql);
        }
        #endregion

        #region 日期相关函数
        /// <summary>
        /// 将日期字符串转换为yyyyMMdd类型的字符串
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static string ConvertDateTimeString(string dateTime)
        {
            CheckParam(dateTime, "日期字符串");
            string rtn;
            try
            {
                System.DateTime d = Convert.ToDateTime(dateTime);
                rtn = d.ToString("yyyyMMdd");
            }
            catch
            {
                rtn = "";
            }
            return rtn;
        }

        /// <summary>
        /// 将8位日期格式yyyyMMdd转换成10位日期格式yyyy-MM-dd
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string Date8To10(string date)
        {
            if (date.Length == 8)
            {
                if (Convert.ToInt32(date) < 19000101)
                {
                    date = "1900-01-01";
                }
                else if (Convert.ToInt32(date) > 20790606)
                {
                    date = "2079-06-06";
                }
                else
                {
                    date = date.Substring(0, 4) + "-" + date.Substring(4, 2) + "-" + date.Substring(6, 2);
                }
            }
            else
                date = "";

            return date;
        }

        /// <summary>
        /// 对10位日期格式的字符串增加天数

        /// </summary>
        /// <param name="date"></param>
        /// <param name="dateAdd"></param>
        /// <returns></returns>
        public static string DaysAdd(string date, int daysAdd)
        {
            try
            {
                return Convert.ToDateTime(date).AddDays(daysAdd).ToString("yyyy-MM-dd");
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 获得输入日期所处的季度的第一个月
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static int FirstMonthOfQuarter(string date)
        {
            int rtn = 0;
            int month = DateTime.Parse(date).Month;
            if (month >= 1 && month <= 3)
            {
                rtn = 1;
            }
            else if (month >= 4 && month <= 6)
            {
                rtn = 4;
            }
            else if (month >= 7 && month <= 9)
            {
                rtn = 7;
            }
            else
            {
                rtn = 10;
            }
            return rtn;
        }

        /// <summary>
        /// 获得输入日期所处月份的天数
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static int GetDaysOfMonth(DateTime date)
        {
            DateTime date1 = date.AddMonths(1);
            DateTime date2 = new DateTime(date1.Year, date1.Month, 1);
            date = date2.AddDays(-1);
            return date.Day;
        }
        #endregion



        #region 读取WebConfig配置
        public static string GetConfigKeyValue(string key)
        {
            return System.Configuration.ConfigurationManager.AppSettings[key];
        }
        #endregion

        /// <summary>
        /// 截取指定长度的字符窜
        /// </summary>
        /// <param name="inputString">输入字符串</param>
        /// <param name="len">以字节为单位</param>
        /// <returns>tempString</returns>
        public static string CutString(string inputString, int len)
        {

            if (len < 0) return inputString;

            ASCIIEncoding ascii = new ASCIIEncoding();
            int tempLen = 0;
            string tempString = "";
            byte[] s = ascii.GetBytes(inputString);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    tempLen += 2;
                }
                else
                {
                    tempLen += 1;
                }

                try
                {
                    tempString += inputString.Substring(i, 1);
                }
                catch
                {
                    break;
                }

                if (tempLen >= len)
                    break;
            }

            //如果tempString的长度小于inputString，则将tempString最后一个字符改为半个省略号
            if (tempString.Length < inputString.Length)
            {
                tempString = tempString.Substring(0, tempString.Length - 1) + "…";
            }

            return tempString;
        }

        /// <summary>
        /// 如果字符串为empty,则返回0
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ConvertEmptyTo0(string s)
        {
            if (s == null || s == "")
            {
                s = "0";
            }
            return s;
        }


        /// <summary>
        /// 检查域帐号是否为有效帐号（在AD中检查）
        /// </summary>
        /// <param name="adUserID"></param>
        /// <returns></returns>
        public static bool CheckADUserID(string adUserID)
        {
            //    bool rtn = true;
            //    DirectoryEntry root = new DirectoryEntry();
            //    root.Path = GetConfigKeyValue("LdapPath");
            //    root.Username = GetConfigKeyValue("LdapUserName");
            //    DirectorySearcher searcher = new DirectorySearcher();
            //    return rtn;
            return true;
        }


        #region 设置BusinessEntity
        /// <summary>
        /// 如果propertyValue不为空字符串则调用be的SetProperty方法
        /// </summary>
        /// <param name="be"></param>
        /// <param name="property"></param>
        /// <param name="propertyValue"></param>
        public static void SetBusinessEntityPropertyByOmmitBlankValue(BusinessEntiry be, string propertyName, string propertyValue)
        {
            //if(propertyValue != null && propertyValue.Trim() != "") //luosk 2009-01-15 改为空串也更新

            if (propertyValue != null)
            {
                be.SetProperty(propertyName, propertyValue);
            }
        }
        #endregion 设置BusinessEntity

        /// <summary>
        /// 将数据库某列的数据合并成一个字符串，以逗号分隔
        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="sql"></param>
        /// <param name="columnName"></param>
        /// <returns></returns>
        public static string GetTableColString(DataManager dataManager, string sql, string columnName)
        {
            string rtn = "";
            SqlDataReader rs = dataManager.selectReader(sql);
            while (rs.Read())
            {
                rtn += ",'" + rs[columnName].ToString() + "'";
            }
            rs.Close();
            if (rtn.Length > 0)
            {
                rtn = rtn.Substring(1);
            }
            //			else
            //			{
            //				rtn = "''";
            //			}				
            return rtn;
        }

        /// <summary>
        /// 设置Money类型的字段值

        /// </summary>
        /// <param name="entity"></param>
        /// <param name="propertyName"></param>
        /// <param name="propertyValue"></param>
        public static void SetMoneyTypePropertyValue(BusinessEntiry entity, string propertyName, string propertyValue)
        {
            if (entity.GetPropertyValue(propertyName) == "")
            {
                if (propertyValue != "")
                    entity.SetProperty(propertyName, propertyValue, DataType.Money);
            }
            else
            {
                if (propertyValue == "")
                    propertyValue = "0";
                entity.SetProperty(propertyName, propertyValue, DataType.Money);
            }
        }


        //--------------------------------------
        #region 发邮件

        public static bool SendMail(MailAddress MessageFrom, string MessageTo, string MessageSubject, string MessageBody)
        {
            MailMessage message = new MailMessage();

            message.From = MessageFrom;
            message.To.Add(MessageTo);              //收件人邮箱地址可以是多个以实现群发
            message.Subject = MessageSubject;
            message.Body = MessageBody;
            message.IsBodyHtml = true;              //是否为html格式
            message.Priority = MailPriority.High;   //发送邮件的优先等级


            SmtpClient sc = new SmtpClient();
            sc.Host = System.Configuration.ConfigurationManager.AppSettings["MailServer"];              //指定发送邮件的服务器地址或IP
            sc.Port = 25;                           //指定发送邮件端口

            //sc.Credentials = new System.Net.NetworkCredential("username@sina.com", "password"); //指定登录服务器的用户名和密码
            try
            {
                sc.Send(message);       //发送邮件

            }
            catch
            {
                return false;
            }
            finally
            {
                message.Dispose();

            }
            return true;
        }

        public static bool SendMail(string MessageTo, string MessageSubject, string MessageBody)
        {
            MailMessage message = new MailMessage();
            MailAddress MessageFrom = new MailAddress("workflow@centaline.com.cn");
            message.From = MessageFrom;
            message.To.Add(MessageTo);              //收件人邮箱地址可以是多个以实现群发
            message.Subject = MessageSubject;
            message.Body = MessageBody;
            message.IsBodyHtml = true;              //是否为html格式
            message.Priority = MailPriority.High;   //发送邮件的优先等级


            SmtpClient sc = new SmtpClient();
            sc.Host = System.Configuration.ConfigurationManager.AppSettings["MailServer"];              //指定发送邮件的服务器地址或IP
            sc.Port = 25;                           //指定发送邮件端口

            //sc.Credentials = new System.Net.NetworkCredential("username@sina.com", "password"); //指定登录服务器的用户名和密码
            try
            {
                sc.Send(message);       //发送邮件

            }
            catch
            {
                return false;
            }
            finally
            {
                message.Dispose();

            }
            return true;
        }

        public static bool SendMailEx(string MessageTo, string MessageSubject, string MessageBody)
        {
            WF.SendMailService.Mail mail = new WF.SendMailService.Mail();
            mail.Url = System.Configuration.ConfigurationManager.AppSettings["SendMailServiceURL"]; ;
            mail.SendMail(MessageSubject, MessageBody, MessageTo);
            return true;
        }
        #endregion

        #region 错误处理
        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="page">页面对象</param>
        /// <param name="e">异常类实例</param>
        public static void ExceptionHandle(System.Web.UI.Page page, Exception e)
        {
            string debugState = System.Configuration.ConfigurationManager.AppSettings["IsDebug"];
            if (debugState != null && debugState.ToLower() == "true")
            {
                throw e;
            }

            //MailAddress mailFrom = new MailAddress("workflow@centaline.com.cn");
            string ipAddr = page.Request.UserHostAddress;
            string mailTo = (System.Configuration.ConfigurationManager.AppSettings["NoticeMailTo"] == null) ? "liuyj.ce@centaline.com.cn" : System.Configuration.ConfigurationManager.AppSettings["NoticeMailTo"].ToString();
            string subject = "重庆中原CCAI系统错误提示";
            string body = "";
            if (page.Session["EmpName"] != null && page.Session["DeptName"] != null)
            {
                body = "员工：" + page.Session["EmpName"].ToString() + "<br>" + "部门："
                      + page.Session["DeptName"].ToString() + "<br>" + "ＩＰ：" + ipAddr
                      + "<br>" + "描述：" + e.Message;

            }
            else
            {
                body = "ＩＰ：" + ipAddr + "<br>" + "描述：" + e.Message;
            }

            try
            {
                SendMailEx(mailTo, subject, body);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            Messages.ShowMessage(page, "系统出现错误，请与系统管理员联系！", true);
        }

        /// <summary>
        /// 通过邮件发送Exception异常信息
        /// </summary>
        /// <param name="control">所属对象，一般用this或this.Page</param>
        /// <param name="e">异常类实例</param>
        public static void SendExceptionMessage(System.Web.UI.Control control, Exception e)
        {
            if (e.Message.IndexOf("线程正被中止") >= 0 || e.Message.IndexOf("正在中止线程") >= 0)
            {
                return;
            }
            System.Net.IPAddress ip = System.Net.IPAddress.Parse(((Page)control).Request.UserHostAddress);
            System.Net.IPHostEntry ihe = System.Net.Dns.GetHostEntry(ip);
            //机器名

            string clientname = ihe.HostName;
            //浏览器

            string NavInfo = ((Page)control).Request.Browser.Browser + "/" + ((Page)control).Request.Browser.Id + "/" + ((Page)control).Request.Browser.Version;
            //操作系统
            string OS = ((Page)control).Request.Browser.Platform;

            //MailAddress mailFrom = new MailAddress("workflow@centaline.com.cn");
            //string ipAddr = ((Page)control).Request.UserHostAddress;
            string ipAddr = "";
            System.Net.IPAddress[] IpArray = ihe.AddressList;
            if (IpArray.Length > 0)
            {
                for (int i = 0; i < IpArray.Length; i++)
                {
                    string temp = IpArray[i].ToString();
                    if (temp.Split('.')[0] == "10")
                    {
                        ipAddr = temp;
                    }
                }
            }
            string mailTo = (System.Configuration.ConfigurationManager.AppSettings["NoticeMailTo"] == null) ? "luosk@centaline.com.cn" : System.Configuration.ConfigurationManager.AppSettings["NoticeMailTo"].ToString();
            string subject = "系统错误提示";
            string body = "";
            if (((Page)control).Session["EmpName"] != null && ((Page)control).Session["DeptName"] != null)
            {
                body = "员工：" + ((Page)control).Session["EmpName"].ToString() + "<br>" + "部门："
                      + ((Page)control).Session["DeptName"].ToString() + "<br>" + "ＩＰ：" + ipAddr
                      + "<br>" + "机器名：" + clientname + "<br>"
                      + "<br>" + "操作系统：" + OS + "<br>"
                      + "<br>" + "浏览器信息： " + NavInfo + "<br>"
                      + "描述：" + e.ToString();

            }
            else
            {
                body = "ＩＰ：" + ipAddr + "<br>" + "描述：" + e.Message;
            }

            try
            {

                SendMailEx(mailTo, subject, body);

            }
            catch (Exception ex)
            {
                throw ex;
            }


        }

        #endregion

        #region  得到客户端操作系统类型


        public static string GetOSNameByUserAgent(string userAgent)
        {
            string osVersion = "未知";

            if (userAgent.Contains("NT 6.1"))
            {
                osVersion = "Windows 7;Windows Server 2008R2";
            }
            else if (userAgent.Contains("NT 6.0"))
            {
                osVersion = "Windows Vista;Windows Server 2008";
            }
            else if (userAgent.Contains("NT 5.2"))
            {
                osVersion = "Windows Server 2003";
            }
            else if (userAgent.Contains("NT 5.1"))
            {
                osVersion = "Windows XP";
            }
            else if (userAgent.Contains("NT 5"))
            {
                osVersion = "Windows 2000";
            }
            else if (userAgent.Contains("NT 4"))
            {
                osVersion = "Windows NT4";
            }
            else if (userAgent.Contains("Me"))
            {
                osVersion = "Windows Me";
            }
            else if (userAgent.Contains("98"))
            {
                osVersion = "Windows 98";
            }
            else if (userAgent.Contains("95"))
            {
                osVersion = "Windows 95";
            }
            else if (userAgent.Contains("Mac"))
            {
                osVersion = "Mac";
            }
            else if (userAgent.Contains("Unix"))
            {
                osVersion = "UNIX";
            }
            else if (userAgent.Contains("Linux"))
            {
                osVersion = "Linux";
            }
            else if (userAgent.Contains("SunOS"))
            {
                osVersion = "Sun OS";
            }
            return osVersion;
        }

        #endregion


        #region 绑定网格数据
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dglist"></param>
        /// <param name="sql"></param>
        public static void BindDataGrid(DataManager dataManager, Com.UI.Web.DataGridEx dglist, string sql)
        {
            dglist.DataManager = dataManager;
            dglist.DataSourceSQL = sql;
            dglist.BindData();
        }
        #endregion


        #region 设置控件只读
        /// <summary>
        /// 设置控件只读
        /// </summary>
        /// <param name="control"></param>
        /// <param name="isReadOnly"></param>
        public static void SetControlReadOnly(System.Web.UI.Control control, bool isReadOnly)
        {
            foreach (System.Web.UI.Control c in control.Controls)
            {
                if (c.ID != null && (c.GetType().Name == "TextBox" || c.GetType().Name == "TextBoxEx"))
                {
                    TextBox t = (TextBox)c;
                    t.ReadOnly = isReadOnly;
                }
                else if (c.ID != null && c.GetType().Name == "CalendarExtender")
                {
                    AjaxControlToolkit.CalendarExtender t = (AjaxControlToolkit.CalendarExtender)c;
                    t.Enabled = false;
                }
                else if (c.ID != null && c.GetType().Name == "RadioButton")
                {
                    RadioButton rb = (RadioButton)c;
                    rb.Enabled = !isReadOnly;
                }
                else if (c.ID != null && c.GetType().Name == "RadioButtonList")
                {
                    RadioButtonList rbl = (RadioButtonList)c;
                    rbl.Enabled = !isReadOnly;
                }
                else if (c.ID != null && c.GetType().Name == "DropDownList")
                {
                    DropDownList d = (DropDownList)c;
                    d.Enabled = !isReadOnly;
                }
                else if (c.ID != null && c.GetType().Name == "CheckBox")
                {
                    CheckBox cb = (CheckBox)c;
                    cb.Enabled = !isReadOnly;
                }
                else if (c.ID != null && c.GetType().Name == "CheckBoxList")
                {
                    CheckBoxList cbl = (CheckBoxList)c;
                    cbl.Enabled = !isReadOnly;
                }
                else if (c.ID != null && c.GetType().Name == "HtmlTable")
                {
                    System.Web.UI.HtmlControls.HtmlTable table = (System.Web.UI.HtmlControls.HtmlTable)c;
                    table.Disabled = isReadOnly;
                }
                else
                {
                    SetControlReadOnly(c, isReadOnly);
                }
            }
        }
        #endregion

        #region 设置控件只读样式
        public static void SetControlReadOnlyStyle(System.Web.UI.Control control)
        {
            foreach (System.Web.UI.Control c in control.Controls)
            {
                if (c.ID != null && (c.GetType().Name == "TextBox" || c.GetType().Name == "TextBoxEx"))
                {
                    TextBox t = (TextBox)c;
                    if (!t.Enabled || t.ReadOnly)
                    {
                        if (t.CssClass == "textfield1")
                        {
                            t.CssClass = "readonlyfield1";
                        }
                        else if (t.CssClass == "textfield2")
                        {
                            t.CssClass = "readonlyfield2";
                        }
                        else if (t.CssClass == "textarea1")
                        {
                            t.CssClass = "readonlyarea1";
                        }
                    }
                }
                else
                {
                    SetControlReadOnlyStyle(c);
                }
            }
        }
        #endregion


    }
}
